package cn.com.bluemoon.daps.model.core.file.validator;

import cn.com.bluemoon.daps.common.constant.DapConstant;
import cn.com.bluemoon.daps.model.core.cache.ModelCacheHelper;
import cn.com.bluemoon.daps.standard.entity.DapSystemCategory;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;


/**
 * 主题分类校验
 *
 * @author Jarod.Kong
 * @date 2021/3/15 14:25
 */
@Slf4j
public class TopicCategoryValidator implements ConstraintValidator<MyTopicCategory, String> {
    private static final String TOPIC_SPLIT_CHAR = "/";

    /**
     * Initializes the validator in preparation for
     * {@link #isValid(Object, ConstraintValidatorContext)} calls.
     * The constraint annotation for a given constraint declaration
     * is passed.
     * <p>
     * This method is guaranteed to be called before any use of this instance for
     * validation.
     * <p>
     * The default implementation is a no-op.
     *
     * @param constraintAnnotation annotation instance for a given constraint declaration
     */
    @Override
    public void initialize(MyTopicCategory constraintAnnotation) {
        // 初始化一次
        ModelCacheHelper.getTopicAndCategoriesByCache();
    }

    @Override
    public boolean isValid(String topics, ConstraintValidatorContext constraintValidatorContext) {
        if (StringUtils.isBlank(topics)) {
            log.error("主题列为必填项");
            return false;
        }
        final Map<String, List<DapSystemCategory>> topicAndCategories = ModelCacheHelper.getTopicAndCategoriesByCache();
        final List<DapSystemCategory> topic2s = topicAndCategories.get(DapConstant.DapStandard.SYSTEM_TOPIC2_NAME);
        final List<DapSystemCategory> categories1 = topicAndCategories.get(DapConstant.DapStandard.SYSTEM_CATEGORY1_NAME);
        final String[] topicsArr = topics.split(TOPIC_SPLIT_CHAR);
        if (topicsArr.length < 2) {
            log.error("主题分类，至少指定主题和一级分类");
            return false;
        }
        final String topic = StrUtil.trim(topicsArr[0]);
        final String category1 = StrUtil.trim(topicsArr[1]);
//        final String category2 = (topicsArr.length == 3) ? StrUtil.trim(topicsArr[2]) : "";
//        final String category3 = (topicsArr.length == 4) ? StrUtil.trim(topicsArr[3]) : "";
        List<String> topicIds = new ArrayList<>(topicsArr.length);
        Optional<DapSystemCategory> topicObj = topic2s.stream()
                .filter(o -> o.getCodeName().equalsIgnoreCase(topic)).findAny();
        if (!topicObj.isPresent()) {
            log.error("主题分类，列值与系统主题匹配失败");
            return false;
        }
        String topicId = topicObj.get().getId();
        topicIds.add(topicId);
        Optional<DapSystemCategory> category1Obj = categories1.stream()
                .filter(o -> o.getParentId().equals(topicId))
                .filter(o -> o.getCodeName().equalsIgnoreCase(category1)).findFirst();
        if (!category1Obj.isPresent()) {
            log.error("主题分类，列值与系统一级分类匹配失败");
            return false;
        }
        String category1Id = category1Obj.get().getId();
        topicIds.add(category1Id);
        log.debug("校验通过，翻译到的主题[{}]=[{}]", topics, String.join(TOPIC_SPLIT_CHAR, topicIds));
        return true;
    }


}
